home *** CD-ROM | disk | FTP | other *** search
- Path: news.WARWICK.NET!usenet
- From: acorn@warwick.net (Peter Kohlberger)
- Newsgroups: comp.lang.c
- Subject: Re: malloc question
- Date: Tue, 12 Mar 1996 16:35:35 GMT
- Organization: Warwick Online
- Message-ID: <4i492m$9jl@news1.warwick.net>
- References: <4htonk$350@news.hklink.net>
- NNTP-Posting-Host: t9-15.warwick.net
- X-Newsreader: Forte Free Agent 1.0.82
-
- alex@station.net (Alex Chu) wrote:
- >Hi everybody,
-
- >I have a question for the following snip C program.
-
- >typedef struct item {
- > int val;
- > struct item *next;
- >} ITEM, *PITEM;
-
- >main()
- >{
- > PITEM head, current;
- > head=(PITEM) malloc(sizeof(ITEM));
- > ^^^^^^^
- > head->val=1;
- >}
-
- >I want to know why need to use the type casting PITEM in front of the
- >malloc ? Please help!
-
- Basically, you need the cast because head is of type "pointer to ITEM"
- and malloc returns type "pointer to void". If you try it without the
- cast, your compiler will complain "cannot convert *void to *ITEM".
- This is just the mechanics of the answer though, and I suspect this
- is not what really puzzles you.
-
- Without the cast, you can not convert *void into *ITEM; with the cast,
- you are allowed to do the conversion. If the conversion is allowed in
- one manner, why is it not allowed in the other manner?
-
- The answer is (mostly) so that the compiler can catch your errors.
- While a pointer to void can be converted to a pointer to any type of
- object, it's desirable to ensure that the conversion is the actual
- intent of the programmer.
-
- Consider the following:
-
- typedef struct item1 {
- int val;
- struct item *next;
- } ITEM1, *PITEM1;
-
- typedef struct item2 {
- int val;
- struct item *next;
- char text[40];
- } ITEM2, *PITEM2;
-
- main()
- {
- PITEM1 head1;
- PITEM2 head2;
-
- head1 =(PITEM1)malloc(sizeof(ITEM1));
- head1->val=1;
-
- head2 =malloc(sizeof(ITEM1)); /* illegal */
- strcpy(head2->text,"Some text for here");
-
- return(0);
- }
-
- If the above call to malloc() without a cast was allowed, head2 would
- be allocated 6 bytes when it needs 46 bytes (in my environment).
- Requiring the cast changes the code to:
-
- head2 =(PITEM1)malloc(sizeof(ITEM1));
-
- which will result in a compiler error.
-
- Peter Kohlberger
- acorn@warwick.net
-
-
-
-